package middlewares

import (
	"fmt"
	"gin-demo/utils/jwt"
	"github.com/gin-gonic/gin"
	"net/http"
)

func JwtAuthMiddleware() func(c *gin.Context) {
	return func(c *gin.Context) {
		authHeader := c.Request.Header.Get("token")
		if authHeader == "" {
			c.JSON(http.StatusOK, gin.H{
				"code": 2003,
				"msg":  "请示头中token为空",
			})
			c.Abort()
			return
		}
		fmt.Println("authHeader = ")
		fmt.Println(authHeader)
		// 按空格分割
		//authHeader = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNjQxOTgxODk3LCJpc3MiOiJteS1wcm9qZWN0In0.QYhShlpY-pTdRp5F-7ujTXqlvSK11vs4xVfgw0vNeT0"
		//parts := strings.SplitN(authHeader, " ", 2)
		//fmt.Println("parts = ")
		//fmt.Println(parts)
		//if !(len(parts) == 2 && parts[0] == "Bearer") {
		//	c.JSON(http.StatusOK, gin.H{
		//		"code": 2004,
		//		"msg":  "请求头中auth格式有误",
		//	})
		//	c.Abort()
		//	return
		//}
		mc, err := jwt.ParseToken(authHeader)
		fmt.Println("错误：")
		fmt.Println(err)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 2005,
				"msg":  "无效的token",
			})
			c.Abort()
			return
		}
		c.Set("username", mc.Username)
		c.Next()
	}
}
